package com.kakame.codenews.base.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.kakame.codenews.base.config.system.SystemConfig;
import com.kakame.codenews.base.util.ImageUtil;

/**
 * <pre>
 * <b>desc:</b> 文件上传下载 
 * <b>auth:</b> ex-hejm
 * <b>date:</b> 2018年6月12日 下午5:28:30
 * </pre>
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

	@Resource
	private FastFileStorageClient fastFileStorageClient;

	/**
	 * <pre>
	 * <b>desc:</b> 多文件上传 
	 * <b>auth:</b> ex-hejm
	 * <b>date:</b> 2018年6月12日 下午5:43:35
	 * </pre>
	 * 
	 * @param uploadFile
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/multi")
	@ResponseBody
	public String[] multi(@RequestParam("upfile") MultipartFile[] uploadFile, HttpServletRequest request,
			HttpSession session) throws Exception {
		String[] urls = new String[uploadFile.length];
		int index = 0;
		for (MultipartFile multipartFile : uploadFile) {
			if (multipartFile.getSize() > 0) {
				String originalFilename = multipartFile.getOriginalFilename();
				// 得到文件后缀名
				String fileExtName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
				// StorePath [group=group1, path=M00/00/00/rBJtj1tKFQSACoRxAAmFdbR27oc188.jpg]
				StorePath storePath = fastFileStorageClient.uploadFile(null, multipartFile.getInputStream(),
						multipartFile.getSize(), fileExtName);
				String group = storePath.getGroup();
				String path = storePath.getPath();
				String url = SystemConfig.get("fastdfs.download.address") + "/" + group + "/" + path;
				urls[index++] = url;
			}
		}
		return urls;
	}

	/**
	 * 用户头像上传
	 * 
	 * @author 何家明 2018年7月15日 下午5:28:55
	 * @param file
	 * @param dataStr
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userIcon")
	@ResponseBody
	public Map<String, String> userIcon(@RequestParam("avatar_file") MultipartFile file,
			@RequestParam("avatar_data") String dataStr, HttpServletRequest request, HttpSession session)
			throws Exception {
		JSONObject data = JSON.parseObject(dataStr);
		int height = (int) data.get("height");
		int width = (int) data.get("width");
		int startX = (int) data.get("x");
		int startY = (int) data.get("y");
		Map<String, String> map = new HashMap<String, String>();

		if (!file.isEmpty() && (height > 0 && width > 0 && startX > 0 && startY > 0)) {
			// 上传文件路径
			String path = request.getServletContext().getRealPath("/userImageFile/");
			// 上传文件名
			String filename = file.getOriginalFilename();
			String fileType = filename.substring(filename.indexOf(".") + 1).toLowerCase();

			String name = UUID.randomUUID().toString() + filename.substring(filename.indexOf("."));
			File filepath = new File(path, name);
			// 判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			// 将上传文件保存到一个目标文件当中
			String imagepath = path + File.separator + name;
			System.out.println(imagepath);
			file.transferTo(new File(imagepath));

			// 开始剪裁
			ImageUtil test = new ImageUtil();
			test.input = new FileInputStream(imagepath);
			test.out = imagepath;
			test.cutImage(fileType, startX, startY, width, height);

			// 更新数据库
			String picPath = request.getContextPath() + File.separator + "userImageFile" + File.separator + name;
//			userService.updateUser(session.getAttribute("username").toString(), picPath);
			session.setAttribute("userPic", picPath);
			map.put("result", picPath);
		}
		// 前台做了校验，不能上传空文件
		return map;
	}
}
